use serde::{Deserialize, Serialize};

use crate::{
    dao::{self, book_name::BookName},
    utils::{
        page::{PagePamas, PageResult},
        response::R,
    },
};

#[tauri::command]
pub async fn book_name_list_to_lable_value(page: PagePamas<String>) -> R<PageResult<LabelValue>> {
    if let Some((count, list)) = dao::book_name::get_page(page.page, page.size, page.data).await {
        let mut values = vec![];
        for i in list {
            values.push(LabelValue {
                label: i.title.clone(),
                value: i.title,
            });
        }
        let result = PageResult::new(page.page, page.size, count, values);
        return R::data(Some(result));
    }
    R::data(Some(PageResult::new(page.page, page.size, 0, vec![])))
}

#[tauri::command]
pub async fn book_name_list() -> R<Vec<BookName>> {
    R::data(dao::book_name::get_list().await)
}


#[tauri::command]
pub async fn update_book_name_info(id: String, title: String) -> R<bool> {
    if id.is_empty() {
        return R::fail("参数错误！");
    }
    let mut book_name = BookName::default();
    book_name.id = id;
    book_name.title = title;
    if !dao::book_name::update_title_tokio(book_name).await {
        return R::fail("更新失败");
    }
    R::success()
}

#[tauri::command]
pub async fn update_book_sort_info(id: String, sort: i16) -> R<bool> {
    if id.is_empty() {
        return R::fail("参数错误！");
    }
    let mut book_name = BookName::default();
    book_name.id = id;
    book_name.sort = sort;
    if !dao::book_name::update_sort_tokio(book_name).await {
        return R::fail("更新失败");
    }
    R::success()
}

#[tauri::command]
pub fn save_book_name(title: String, content: String) -> R<u64> {
    let mut info = BookName::default();
    info.title = title;
    info.content = content;
    if let Some(id) = dao::book_name::save(info) {
        return R::data(Some(id));
    }
    R::fail("保存失败！")
}

#[tauri::command]
pub async fn delete_book_name(id: String) -> R<bool> {
    if let Some(num) = dao::momento::get_count_by_book_id(id.clone()).await {
        if num {
            return R::fail("分类有子集，不能删除！");
        } else {
            if dao::book_name::delete_by_id(id).await {
                return R::success();
            }
        }
    }
    R::fail("删除失败！")
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct LabelValue {
    pub label: String,
    pub value: String,
}

impl Default for LabelValue {
    fn default() -> Self {
        Self {
            label: String::from(""),
            value: String::from(""),
        }
    }
}
